
class ListNode {
 int val;
 ListNode next;
 ListNode() {}
 ListNode(int val) { this.val = val; }
 ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }

/**
 * 24. 两两交换链表中的节点
 * https://leetcode.cn/problems/swap-nodes-in-pairs/description/
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;

        ListNode newHead = new ListNode();
        newHead.next = head;

        ListNode prev, cur, next, nnext;

        prev = newHead;
        cur = prev.next;
        next = cur.next;
        nnext = next.next;

        while(cur != null && next != null) {
            prev.next = next;
            next.next = cur;
            cur.next = nnext;

            prev = cur;
            cur = nnext;
            if(cur == null) break;
            next = cur.next;
            if(next == null) break;
            nnext = next.next;
        }

        return newHead.next;
    }
}